﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WWNotice
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            System.Timers.Timer timer = new System.Timers.Timer(1000 * 5);
            int t = 0;
            int c = 0;
            timer.Elapsed += delegate
            {
                Notice.getWindows();
                t++;
                if (t > c * c && DateTime.Now.Hour < 23 && DateTime.Now.Hour > 7)
                {
                    DingDing text1 = new DingDing("淘宝服务器系统异常，请尽快通知恢复@沙杰", "通知检测");
                    string a = Notice.GetResponse("http://47.101.221.173:888/notice/wangwang");
                    if (!a.StartsWith("{\"code\":200"))
                    {
                        Notice.GetJsonRequest(JsonConvert.SerializeObject(text1));
                        c++;
                    }
                    else
                    {
                        c = 0;
                    }
                    t = 0;

                }
            };
            timer.Start();

        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }

    public class Notice
    {
        public static string message = "### 接收到旺旺用户信息@所有人 ";
        static string title = "重要消息";
        public static void getWindows()
        {
            Process[] process = Process.GetProcesses();
            List<string> b = new List<string>();
            foreach (Process p in process)
            {
                string text = p.MainWindowTitle.ToString();
                if (text.Contains("系统消息"))
                {
                    string user = text.Substring(0, text.Length - 6);
                    DingDing text1 = new DingDing(message, title);
                    GetJsonRequest(JsonConvert.SerializeObject(text1));

                }
                if (!string.IsNullOrEmpty(text)) b.Add(text);
            }
        }

        public static string GetJsonRequest(string requestJson, string requestUrl = "https://oapi.dingtalk.com/robot/send?access_token=ca39d4ae62d4ed2431f800ac2933eaf07d0ad1dc019f5d4a720d5138c3cdadfa", int time = 10000)
        {
            var result = string.Empty;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUrl);
            //发送post请求,相应的请求参数
            byte[] data = Encoding.GetEncoding("utf-8").GetBytes(requestJson);
            request.Method = "Post";
            request.Accept = "application/json";
            request.ContentLength = data.Length;
            request.ContentType = "application/json; charset=utf8";
            request.Timeout = time;
            //请求流
            Stream requetStream = request.GetRequestStream();
            requetStream.Write(data, 0, data.Length);
            requetStream.Close();
            //响应流
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream responseStream = response.GetResponseStream();
            if (responseStream != null)
            {
                StreamReader streamReader = new StreamReader(responseStream, Encoding.GetEncoding("UTF-8"));
                //获取返回信息
                result = streamReader.ReadToEnd();
                streamReader.Close();
                responseStream.Close();
            }

            return result;
        }

        /// <summary> Get方法获取某URL的页面内容</summary>
        /// <param name="url">网址</param>
        /// <param name="encoding">编码</param>
        /// <returns>页面内容</returns>
        public static string GetResponse(string url, string encoding = "UTF-8", int timeOut = 5000)
        {
            string result = string.Empty;
            try
            {
                ////处理HttpWebRequest访问https有安全证书的问题（ 请求被中止: 未能创建 SSL/TLS 安全通道。）
                //ServicePointManager.Expect100Continue = true;
                //ServicePointManager.ServerCertificateValidationCallback += (s, cert, chain, sslPolicyErrors) => true;
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls | SecurityProtocolType.Ssl3;
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                //request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; QQWubi 133; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; CIBA; InfoPath.2)";
                request.Timeout = timeOut;
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                Stream resStream = response.GetResponseStream();
                Encoding encode = Encoding.GetEncoding(encoding);
                if (resStream != null)
                {
                    StreamReader readStream = new StreamReader(resStream, encode);
                    Char[] read = new Char[256];
                    int count = readStream.Read(read, 0, 256);
                    while (count > 0)
                    {
                        String str = new String(read, 0, count);
                        result = result + str;
                        count = readStream.Read(read, 0, 256);
                    }
                    resStream.Close();
                }
            }
            catch
            {
                return string.Empty;
            }
            return result;
        }
    }
    public class DingDing
    {
        public string msgtype { get; set; } = "markdown";
        public TEXT text { get; set; }
        public MarkDown markdown { get; set; }
        public AT at { get; set; }
        public DingDing(string message, string title = "")
        {
            text = new TEXT(message);
            at = new AT();
            markdown = new MarkDown(title, message);
        }
    }

    public class TEXT
    {
        public string content { get; set; }
        public TEXT(string message)
        {
            content = message;
        }
    }

    public class AT
    {
        public string[] atMobiles { get; set; }

        public bool isAtAll { get; set; } = true;
    }

    public class MarkDown
    {
        public string title { get; set; }

        public string text { get; set; }

        public MarkDown(string title, string text)
        {
            this.title = title;
            this.text = text;
        }
    }
}

